from sklearn.cluster import KMeans              # 导入KMeans聚类算法
from sklearn.datasets import make_blobs         # 导入make_blobs函数用于生成聚类数据
from sklearn.metrics import silhouette_score    # 导入silhouette_score,轮廓系数，用于评估聚类效果
import matplotlib.pyplot as plt                 # 导入matplotlib用于数据可视化

# 生成样本数据（3个聚类，1000个点）
X, y = make_blobs(n_samples=1000, centers=3, random_state=6)

# Kmeans聚类模型训练
kmeans = KMeans(n_clusters=3, random_state=6)
kmeans.fit(X)

# 获取聚类标签和质心
labels = kmeans.labels_
centroids = kmeans.cluster_centers_

# 评估聚类效果：轮廓系数
print("轮廓系数：", silhouette_score(X, labels))

# 可视化结果
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', s=50, alpha=0.7)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, marker='X')
plt.title('K-Means Clustering(k=3)')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()